
/*
** init_cnf.c for raytracer in /home/le_e//project/project_b2/raytracer
** 
** Made by canh-kiet le
** Login   <le_e@epitech.net>
** 
** Started on  Thu Mar 29 11:28:51 2012 canh-kiet le
** Last update Mon Apr 30 21:06:17 2012 canh-kiet le
*/

#include	"rt.h"

static int     	check_line(char **tab, t_check check, int line_err)
{
  int		i;
  int		ind;

  i = 0;
  ind = -1;
  if (my_strcmp(tab[0], "END") == 0)
    return (-1);
  while (check.name_info[i])
    {
      if (my_strcmp(tab[0], check.name_info[i]) == 0)
	ind = i;
      i++;
    }
  if (tab[0] == NULL && ind == -1)
    disp_err(tab[0], line_err, "Missing keyword END");
  if (ind == -1)
    disp_err(tab[0], line_err, "Invalid information");
  return (ind);
}

static int     	init_structs(t_scene *sc, int fd, t_check *check, int flag)
{
  char		**tab;
  char		*line;
  int		ind;

  ind = 0;
  line = NULL;
  while (ind >= 0 && (line = get_next_line(fd)))
    {
      sc->line_err++;
      tab = str_to_word_tab(line);
      ind = check_line(tab, check[flag], sc->line_err);
      if (ind >= 0)
	{
	  if (flag == SET)
	    fill_eye(sc, tab, ind);
	  else if (flag == LGT)
	    fill_lgt(sc->lgt, tab, ind, sc->line_err);
	  else
	    fill_obj(sc->obj, tab, ind, sc->line_err);
	}
      free(line);
      free_tab(tab);
    }
  return (fd);
}

void		init_cnf(char *filename, t_scene *sc)
{
  int		flag;
  int		fd;
  char		*line;
  t_check	*check;

  check_filename(filename);
  check = xmalloc(4 * sizeof(*check));
  init_check(&check);
  fd = xopen(filename, O_RDONLY);
  sc->obj = NULL;
  sc->lgt = NULL;
  sc->line_err = 0;
  while ((line = get_next_line(fd)))
    {
      sc->line_err++;
      epur_str(line);
      if (line[0] == 0);
      else if ((flag = det_type(line, check, sc)) != -1)
	fd = init_structs(sc, fd, check, flag);
      else
	disp_err(line, sc->line_err, "Bad name information");
      free(line);
    }
  xclose(fd);
  free(check);
}
